package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.doman.pojo.Clazz;
import com.itheima.doman.pojo.ClazzQueryParam;
import com.itheima.doman.pojo.PageResult;
import com.itheima.exception.ClazzDeleteException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StdMapper;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StdMapper stdMapper;

    /**
     * 添加班级
     * @param clazz
     */
    @Override
    public void addClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insertClazz(clazz);
    }

    /**
     *  查询全部班级
     * @return
     */
    @Override
    public List<Clazz> findAll() {
        List<Clazz> clazzList = clazzMapper.findAll();
        return clazzList;
    }

    /**
     *  分页查询
     * @param clazzQueryParam
     * @return
     */
    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        List<Clazz> clazzList = clazzMapper.list(clazzQueryParam);
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult<>(p.getTotal(),p.getResult());
    }

    /**
     *  根据id删除班级
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        Integer byClazzId = stdMapper.getByClazzId(id);
        if (byClazzId > 0){
            throw new ClazzDeleteException(MessageConstant.DELETE_CLAZZ_HAVE_STUDENT_FAIL);
        }
        clazzMapper.deleteById(id);
    }

    /**
     *  根据id查询班级
     * @param id
     * @return
     */
    @Override
    public Clazz findById(Integer id) {
        return clazzMapper.findById(id);
    }

    /**
     *  修改班级
     * @param clazz
     */
    @Override
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateClazz(clazz);
    }


}
